package com.itic.appbase.applications.sys.common.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itic.appbase.applications.cacheutils.CodeCache;
import com.itic.appbase.applications.cacheutils.ResourceCache;
import com.itic.appbase.applications.sys.code.persistence.dao.CodeDetailDao;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetail;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetailExample;
import com.itic.appbase.applications.sys.code.persistence.model.CodeDetailExample.Criteria;
import com.itic.appbase.applications.sys.code.vo.CodeDetailVo;
import com.itic.appbase.applications.sys.common.service.InnerCommonService;
import com.itic.appbase.applications.sys.org.persistence.dao.OrgDao;
import com.itic.appbase.applications.sys.org.persistence.model.Org;
import com.itic.appbase.applications.sys.org.persistence.model.OrgExample;
import com.itic.appbase.applications.sys.region.persistence.dao.RegionDao;
import com.itic.appbase.applications.sys.region.persistence.model.Region;
import com.itic.appbase.applications.sys.relation.persistence.dao.RoleResourceDao;
import com.itic.appbase.applications.sys.resource.persistence.dao.ResourceDao;
import com.itic.appbase.applications.sys.resource.persistence.model.Resource;
import com.itic.appbase.applications.sys.resource.persistence.model.ResourceExample;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.BaseService;
import com.itic.appbase.framework.common.service.ViewResolverService;
import com.itic.appbase.framework.utils.PropertyGetter;
import com.itic.appbase.framework.utils.ReflectHelper;
import com.itic.appbase.framework.utils.StringHelper;

@Service("innerCommonService")
public class InnerCommonServiceImpl
        extends BaseService
        implements InnerCommonService, ViewResolverService{
    
    //private static final String PAGE_404 = "errors/404";
    
    @Autowired
    private RegionDao regionDao;
    @Autowired
    private CodeDetailDao codeDetailDao;
    @Autowired
    private ResourceDao resourceDao;
    @Autowired
    private RoleResourceDao roleResourceDao;
    @Autowired
    private OrgDao orgDao;
    

    /**
     * 根据代码获取名称
     * 
     * @param obj
     * @param codeMap
     * @return
     */
    @Override
    public Object getNameByCode(Object obj, Map<String, String> codeMap) {
        if (null != codeMap && !codeMap.isEmpty()) {
            Iterator<String> it = codeMap.keySet().iterator();
            List<CodeDetail> codeList = null;
            CodeDetailVo codeDetailVo = new CodeDetailVo();
            while (it.hasNext()) {
                // 获取key
                String type = it.next();
                codeDetailVo.setType(codeMap.get(type));
                codeList = getCodeDetail(codeDetailVo);
                if (null != codeList) {
                    // 数据字段转换前的code值
                    String code = (String) ReflectHelper.getValueByFieldName(obj, type);
                    if (StringHelper.isNotBlank(code)) {
                        // 查找名称
                        for (CodeDetail codeDetail : codeList) {
                            if (code.equals(codeDetail.getCode())) {
                                ReflectHelper.setValueByFieldName(obj, type, codeDetail.getName());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return obj;
    }

    /**
     * 查询代码表集合
     * 
     * @param codeDetailVo
     *            封装type和filter
     * @return List：CodeDetail
     */
    @Override
    public List<CodeDetail> getCodeDetail(CodeDetailVo codeDetailVo) {
        List<CodeDetail> codeList = new ArrayList<CodeDetail>();
        if (null != codeDetailVo && StringHelper.isNotBlank(codeDetailVo.getType())) {
            // 缓存获取
            codeList = CodeCache.get(codeDetailVo.getType());
            // 数据库查找
            if (null == codeList) {
                CodeDetailExample detailExample = new CodeDetailExample();
                detailExample.setOrderByClause("ORDER_NO asc");
                Criteria criteria = detailExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
                criteria.andTypeEqualTo(codeDetailVo.getType());
                codeList = codeDetailDao.selectByExample(detailExample);
                // 缓存
                CodeCache.put(codeDetailVo.getType(), codeList);
            }
            // 返回集合过滤
            if (StringHelper.isNotBlank(codeDetailVo.getFilterCode())) {// 过滤不需要的代码
                String[] filters = codeDetailVo.getFilterCode().split(",");
                Arrays.sort(filters);
                String code = "";
                List<CodeDetail> filteredList = new ArrayList<CodeDetail>();
                for (CodeDetail codeDetail : codeList) {
                    code = codeDetail.getCode();
                    if (StringHelper.isNotBlank(code) && Arrays.binarySearch(filters, code) < 0) {
                        filteredList.add(codeDetail);
                    }
                }
                codeList.clear();
                return filteredList;
            }
        }
        return codeList;
    }

    /**
     * 根据org(code/pCode/clazz)获取组织机构树
     * 
     * @param queryOrg
     * @return
     */
    @Override
    public List<Org> getOrgTree(Org queryOrg) {
        // code不为null时，以code查询，pCode置空
        if (null != queryOrg && StringHelper.isNotBlank(queryOrg.getCode())) {
            queryOrg.setpCode(null);
        }
        String isMysql = PropertyGetter.getString("app.db.type");
    	if( StringHelper.isNotBlank(isMysql)&&"mysql".equals(isMysql) ){
    		 OrgExample example = new OrgExample();
	   		 com.itic.appbase.applications.sys.org.persistence.model.OrgExample.Criteria criteria = example.createCriteria();
	   		 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		 if(StringHelper.isNotBlank(queryOrg.getpCode())){
	   			 //criteria.andCodeEqualTo(queryOrg.getpCode());
	   			 criteria.andPCodeEqualTo(queryOrg.getpCode());
	   		 }
	   		 List<Org> list = orgDao.selectByExample(example);
	   		 if( list.size() > 0 ){
	   			 example.clear();
	   			 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   			 ArrayList<String> idList = new ArrayList<String>();
	   			 for( Org temp : list ){
	   				 idList.add(temp.getCode());
	   			 }
	   			 criteria.andPCodeIn(idList);
	   			 return orgDao.selectByExample(example);
	   			 //list.addAll(list2);
	   		 }else{
	   			 return list;
	   		 }
    		 
    	}else{
    		 return orgDao.selectOrgTree(queryOrg);
    	}
        //return orgDao.selectOrgTree(queryOrg);
    }

    /**
     * 根据组织机构code获取组织机构对象
     * 
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public Org getOrgByCode(String code) {
        Org org = null;
        if (StringHelper.isNotBlank(code)) {
            Org orgTemp = new Org();
            orgTemp.setIsEffective(DBConst.TRUE);
            orgTemp.setCode(code);
            
            org = orgDao.selectOrgByCode(orgTemp);
           
        }
        return org;
    }

    /**
     * 根据行政区划id获得行政区划
     */
    @Override
    public Region getRegionById(String id) {
        if (StringHelper.isNotBlank(id)) {
            return regionDao.selectByPrimaryKey(id);
        }
        return null;
    }

    /**
     * 
     */
    @Override
    public List<Region> selectRegionList(Region region) {
        // id不为null时，以id查询，pId置空
        if (null != region && StringHelper.isNotBlank(region.getId())) {
            region.setpId(null);
        }
        return regionDao.selectRegionList(region);
    }

    /**
     * 根据用户id，查询用户所拥有的资源
     * 
     * @param userId
     * @return List<Resource>
     */
    @Override
    public List<Resource> getResourceByUserId(String userId) {
        if (StringHelper.isNotBlank(userId)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("dbTrue", DBConst.TRUE);// 可用的代码表
            map.put("userId", userId);// 用户id
            return roleResourceDao.getResourceByUserId(map);
        }
        return new ArrayList<Resource>();
    }

    /**
     * 根据url获取资源
     */
    @Override
    public Resource getResourceByUrl(String url) {
        Resource resource = null;
        if (StringHelper.isNoneBlank(url)) {
            // 缓存获取
            resource = ResourceCache.get(url);
            if (null == resource) {
                ResourceExample example = new ResourceExample();
                example.createCriteria().andUrlEqualTo(url).andIsEffectiveEqualTo(DBConst.TRUE);
                List<Resource> resources = resourceDao.selectByExample(example);
                if (null != resources && !resources.isEmpty()) {
                    resource = resources.get(0);
                    // 缓存放置
                    ResourceCache.put(url, resource);
                } 
            }
        }
        return resource;
    }

    /**
     * 根据url获取资源名称
     */
    @Override
    public String getResourceNameByUrl(String url) {
        Resource r = this.getResourceByUrl(url);
        return null != r ? r.getName() : "";
    }


    /**
     * 资源树
     * 
     * @param resource
     * @return
     */
    @Override
    public List<Resource> resourceTree(Resource resource) {

        String isMysql = PropertyGetter.getString("app.db.type");
    	if( StringHelper.isNotBlank(isMysql)&&"mysql".equals(isMysql) ){
    		 ResourceExample example = new ResourceExample();
	   		 com.itic.appbase.applications.sys.resource.persistence.model.ResourceExample.Criteria criteria = example.createCriteria();
	   		 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   		 if(StringHelper.isNotBlank(resource.getpId())){
	   			 //criteria.andCodeEqualTo(queryOrg.getpCode());
	   			 criteria.andPIdEqualTo(resource.getpId());
	   		 }
	   		 List<Resource> list = resourceDao.selectByExample(example);
	   		 if( list.size() > 0 ){
	   			 example.clear();
	   			 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   			 ArrayList<String> idList = new ArrayList<String>();
	   			 for( Resource temp : list ){
	   				  idList.add(temp.getId());
	   			 }
	   			 criteria.andPIdIn(idList);
	   			 return resourceDao.selectByExample(example);
	   		 }else{
	   			 return list;
	   		 }
    	}else{
    		return resourceDao.selectResourceList(resource);
    	}
    }
    
    /**
     * 根据url获得资源返回对应页面的映射
     * 
     * @param url
     * @return resourceName
     */
    @Override
    public String getView(Object url) {
        // Resource r = this.getResourceByUrl(String.valueOf(url));
        // TODO 表中加字段， 更新实体
        //return null != r ? r.getReturnPath() : PAGE_404;
        return null;
    }

}
